package com.example.filesharing.handler;


import com.example.filesharing.utils.FileUtils;
import com.yanzhenjie.andserver.RequestHandler;
import com.yanzhenjie.andserver.upload.HttpFileUpload;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.httpcore.HttpException;
import org.apache.httpcore.HttpRequest;
import org.apache.httpcore.HttpResponse;
import org.apache.httpcore.entity.StringEntity;
import org.apache.httpcore.protocol.HttpContext;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class FileUploadHandler implements RequestHandler {
    @Override
    public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
        File file=new File(FileUtils.fileDirectory);//临时文件的存放目录
        FileItemFactory fileItemFactory = new DiskFileItemFactory(10*1024 * 1024, file);//第一个参数是缓存的大小
        HttpFileUpload httpFileUpload=new HttpFileUpload(fileItemFactory);
        String name=null;
        boolean isFinished=false;
        String errMsg="";
        try {
            List<FileItem> fileItemList = httpFileUpload.parseRequest(request);
            for (FileItem fileItem : fileItemList) {
                if(fileItem.isFormField()){//普通参数
                    name = fileItem.getName();
                    String string = fileItem.getString();
                    System.out.println("上送的参数名："+name+",参数值："+string);
                }else{//文件
                    String fieldName = fileItem.getFieldName();
                    long size = fileItem.getSize();//文件大小
                    String contentType = fileItem.getContentType();
                    if(name==null||name.length()<2){
                        name=fileItem.getName();
                    }
                    System.out.println("上传的参数，文件大小："+size+"字节,文件名："+name+"，类型："+contentType+"，表单名字："+fieldName);
                    File uploadFile=new File(file,name);
                    fileItem.write(uploadFile);//将文件写入存储卡中
                    isFinished=true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            errMsg=e.getMessage();
        }

        if(isFinished){
            response.setEntity(new StringEntity("文件上传完成！","utf-8"));
        }else {
            response.setEntity(new StringEntity("文件上传失败,服务器未接收到任何文件！错误信息："+errMsg,"utf-8"));
        }
        response.setHeader("Content-Type","text/html;charset=utf-8");
    }
}
